package newtank.network.server.handler;

import com.alibaba.fastjson.JSONArray;
import entity.Direction;
import entity.Position;
import io.netty.channel.ChannelHandlerContext;
import newtank.data.ConnectionSignal;
import newtank.network.server.registry.ChannelRegistry;
import newtank.view.context.TankViewContext;
import server.GpcRequest;
import server.netty.GpcDataPackage;
import sun.security.provider.MD5;
import tool.GlobalUniqueGenerator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 环境装在配置数据处理器
 * @author lijiahao
 * @since 2022/1/28
 */
public class EnvironmentLoadDataHandler extends AbstractDataHandler{

    private final Map<String, TankViewContext> viewTankContextMap = new HashMap<>();

    @Override
    public void handle(ChannelHandlerContext ctx, GpcDataPackage data) {
        //响应数据封装
        ConnectionSignal response = new ConnectionSignal();
        response.setIndex(GlobalUniqueGenerator.getGlobalId());
        response.setUnique(data.getUnique() + response.getIndex());
        //注册坦克
        TankViewContext tankViewContext = new TankViewContext(900, 750);
        tankViewContext.setTankId(response.getUnique()+":"+"tank_"+GlobalUniqueGenerator.getTankId());
        viewTankContextMap.put(tankViewContext.getTankId(), tankViewContext);
        ChannelRegistry.registry(tankViewContext.getTankId(), ctx);
        response.setStatus(0);
        response.setCode(1);
        GpcRequest gpcRequest = new GpcRequest();
        gpcRequest.setHeader("MD5_VERSION", new MD5().toString());
        gpcRequest.setHeader("WINDOW_WIDTH", "900");
        gpcRequest.setHeader("WINDOW_HEIGHT", "750");
        gpcRequest.setHeader("WINDOW_BACKCOLOR", "BLUE");
        gpcRequest.setHeader("UNIQUE", data.getUnique() + response.getIndex());
        //获取所有坦克信息
        List<TankViewContext> viewContextList = new ArrayList<>(viewTankContextMap.values());
        gpcRequest.setHeader("TANK_CONTEXT", JSONArray.toJSONString(viewContextList));
        response.setRouteRequest(gpcRequest);
        ChannelRegistry.informAll(response);
    }

    public TankViewContext getTankViewContext(String unique) {
        return viewTankContextMap.getOrDefault(unique, null);
    }

    public void update(String unique, Position position, Direction direction,  int version) {
        TankViewContext tankViewContext = getTankViewContext(unique);
        tankViewContext.setPosition(position);
        tankViewContext.setDirection(direction);
        tankViewContext.setVersion(version);
        viewTankContextMap.put(unique, tankViewContext);
    }
}
